import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { defineConfig, loadEnv } from 'vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus';
import viteCompression from 'vite-plugin-compression';
import vueJsx from '@vitejs/plugin-vue-jsx'
import importPlugin from '@opentiny/vue-vite-import'
const pathResolve = (dir) => {
  return resolve(__dirname, '.', dir);
};

const alias = {
  '@': pathResolve('./src/'),
};

const viteConfig = defineConfig((mode) => {
  const env = loadEnv(mode.mode, process.cwd());
  return {
    plugins: [vue(),
      vueJsx(),
      vueSetupExtend(), viteCompression(),
      importPlugin(
          [
            {
              libraryName: '@opentiny/vue'
            },
            {
              libraryName: `@opentiny/vue-icon`,
              customName: (name) => {
                return `@opentiny/vue-icon/lib/${name.replace(/^icon-/, '')}.js`
              }
            }
          ],
          'pc' // 此配置非必选，按需配置(pc|mobile|mobile-first)
      )
    ],
    root: process.cwd(),
    resolve: { alias },
    base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
    optimizeDeps: {
      exclude: ['vue-demi']
    },
    server: {
      host: '0.0.0.0',
      port: 9951
    },
    build: {
      outDir: 'dist',
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//).groups.moduleName ?? 'vender';
            }
          },
        },
      },
    },
    css: { preprocessorOptions: { css: { charset: false } } },
    define: {
      'process.env': Object.assign({}, process.env),
      __NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
      __NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
    },
  };
});

export default viteConfig;
